﻿using Nito.AsyncEx;
using System;
using System.Threading.Tasks;

namespace YWM.Communication
{
    public abstract class CommunicationUtil
    {
        /// <summary>
        /// 异步锁对象
        /// </summary>
        protected readonly AsyncLock _mutex = new AsyncLock();

        private int _delay = 10;
        /// <summary>
        /// 每次循环延时(ms)
        /// </summary>
        public int Delay
        {
            get
            {
                return _delay;
            }
            set
            {
                if (value > 0 || value < ReceiveTimeout / 2)
                {
                    _delay = value;
                }
            }
        }

        /// <summary>
        /// 发送超时时间
        /// </summary>
        protected virtual int SendTimeout { get; set; } = 2000;

        /// <summary>
        /// 接收超时时间
        /// </summary>
        protected virtual int ReceiveTimeout { get; set; } = 2000;

        /// <summary>
        /// 是否连接
        /// </summary>
        public abstract bool Connected { get; }

        /// <summary>
        /// 连接
        /// </summary>
        /// <param name="ipOrPortName">IP地址或串口名</param>
        /// <param name="portOrBaudrate">端口或波特率</param>
        /// <returns></returns>
        public abstract (bool, Exception) Connect(string ipOrPortName, int portOrBaudrate);

        /// <summary>
        /// 异步发送并接收
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public abstract Task<(byte[], Exception)> SendAndReceiveAsync(byte[] buffer);

        /// <summary>
        /// 断开连接
        /// </summary>
        public abstract void Disconnect();
    }
}
